import 'package:acgn_pioneer/models/base_model.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../public.dart';

class QuotaPage extends StatefulWidget {
  QuotaPage({Key key}) : super(key: key);
  @override
  _QuotaPageState createState() => _QuotaPageState();
}

class _QuotaPageState extends State<QuotaPage>
    with AutomaticKeepAliveClientMixin {
  RefreshController _refreshController = RefreshController();
  Map<String, dynamic> userLimit = {
    'pager': PagerModel.fromJson({}),
    'data': []
  };
  bool isInitLoaded = false;
  @override
  void initState() {
    super.initState();
    requestHanddle();
  }

  Future requestHanddle() async {
    int page = userLimit['pager'].page + 1;
    return UserService.getUserLimit(
        {'page': page, 'size': userLimit['pager'].size}).then((res) {
      userLimit['data'].addAll(res.data);
      // 修复服务端返回page为总页数，这里我们需要的是当前页码
      res.pager.page = page;
      if (res.pager.total <= page * res.pager.size) {
        _refreshController.loadNoData();
      } else {
        userLimit['pager'] = res.pager;
        _refreshController.loadComplete();
      }
      isInitLoaded = true;
      setState(() {});
      return res;
    }).catchError((err) {
      isInitLoaded = true;
      _refreshController.loadFailed();
      setState(() {});
    });
  }

  getQuota(item) {
    switch (item.optType) {
      case 1:
        return '+￥' + StringUtil.exchangeRMB(item.gotNum, 1);
      case 2:
        return '-￥' + StringUtil.exchangeRMB(item.costNum, 1);
      default:
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    int len = userLimit['data'].length;
    return RefreshConfig(
        child: SmartRefresher(
            enablePullDown: false,
            enablePullUp: isInitLoaded && len > 0,
            controller: _refreshController,
            onLoading: requestHanddle,
            child: isInitLoaded
                ? (len > 0
                    ? ListView.builder(
                        shrinkWrap: true,
                        itemCount: len,
                        itemBuilder: (BuildContext context, index) {
                          return _getItem(userLimit['data'][index]);
                        })
                    : EmptyComponent())
                : LoadingComponent()));
  }

  Widget _getItem(item) {
    return Container(
        padding: EdgeInsets.only(left: 16, right: 16, top: 10, bottom: 10),
        child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                Text('${item.desc}',
                    style: TextStyle(
                        fontSize: 14, height: 1.75, color: Colors.white)),
                Text(
                    '${StringUtil.formatDate(item.updatedTime, 'yyyy.MM.dd hh:mm:ss')}',
                    style: TextStyle(
                        fontSize: 12,
                        height: 1.5,
                        color: ColorUtil.rgba(255, 255, 255, 0.6)))
              ]),
              Column(children: [
                Text(
                  '${getQuota(item)}',
                  style: TextStyle(fontSize: 16, color: Colors.yellow),
                )
              ]),
            ]));
  }

  @override
  bool get wantKeepAlive => true;
}
